<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\Article;
use App\Model\ArticleTag;
use App\Model\Tag;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class TagController extends AbstractController
{
    #[GetMapping(path: '/sys/tag/list')]
    public function list()
    {
        $name = $this->request->input('name', '');
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);

        $list = Tag::query()
            ->when($name, function ($query) use ($name) {
                return $query->where('name', 'like', '%' . $name . '%');
            })
            ->select('id', 'sort', 'name', 'create_time as createTime', 'update_time as updateTime')->forPage($pageNum, $pageSize)->get();
        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = Article::query()->count();
        $data['pages'] = ceil($data['total'] / $pageSize);
        $data['records'] = $list;
        return success($data);
    }

    #[RequestMapping(path: '/sys/tag',methods: ['POST','PUT'])]
    public function category()
    {
        $params = $this->request->all();
        if (isset($params['id'])){
            Tag::query()->where('id', $params['id'])->update([
                'name' => $params['name'],
                'sort' => $params['sort'],
            ]);
            return success();
        }
        Tag::query()->create($params);
        return success();
    }

    #[DeleteMapping(path: '/sys/tag/delete/{ids}')]
    public function delete($ids)
    {
        try {
            $idArr = explode(',', $ids);
            Db::beginTransaction();
            foreach ($idArr as $id) {
                $category = Tag::query()->where('id', $id)->first();
                if ($category) {
                    Tag::query()->where('id', $id)->delete();
                    ArticleTag::query()->where('tag_id', $id)->delete();
                }
            }
            Db::commit();
            return success();
        } catch (\Throwable $e) {
            Db::rollBack();
            logInfo('delete', $e->getMessage(), 'tag');
        }

    }
}
